<template>
  <div>
    <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
    <div class="container">
      <TableCustom :columns="columns" :tableData="tableData" :hasToolbar="true" :hasPagination="true" :total="page.total"
                   :currentPage="page.index" :pageSize="page.size" :changePage="changePage" :refresh="getData">
        <template #publicationNumber="{ rows }">
          <span class="link" @click="patentView(rows.linkToZhihuiya)">{{ rows.publicationNumber }}</span>
        </template>

        <template #secondTech="{ rows }">
          <el-select v-if="rows.editing"
              v-model="rows.secondTech"
              multiple
              placeholder="Select"
              style="width: 240px"
          >
            <el-option
                v-for="item in techOptions2"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>

          <template v-else>
            <el-tag style="margin-left: 3px;margin-top: 3px" type="success" v-for="tag in rows.secondTech" :key="tag">{{ tag }}</el-tag>
          </template>
        </template>

        <template #firstTech="{ rows }">
          <el-select v-if="rows.editing"
                     v-model="rows.firstTech"
                     multiple
                     placeholder="Select"
                     style="width: 240px"
          >
            <el-option
                v-for="item in techOptions1"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
          <template v-else>
<!--            <el-tag v-if="rows.firstTech.length>0" style="margin-left: 3px;margin-top: 3px" type="success" v-for="tag in rows.firstTech" :key="tag">{{ tag }}</el-tag>-->
            <el-tag style="margin-left: 3px;margin-top: 3px" type="success">{{ rows.firstTech }}</el-tag>
          </template>
        </template>


        <template #operator="{ rows, index }">
          <template v-if="!rows.editing">
            <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(rows)">
              编辑
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="">
              删除
            </el-button>
          </template>
          <template v-else>
            <el-button type="success" size="small" :icon="Select" @click="handleSave(rows)">
              保存
            </el-button>
            <el-button type="default" size="small" :icon="CloseBold" @click="handleCancel(rows, index)">
              取消
            </el-button>
          </template>
        </template>
      </TableCustom>

    </div>
    <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="visible" width="700px" destroy-on-close
               :close-on-click-modal="false" @close="closeDialog">
      <TableEdit :form-data="rowData" :options="options" :edit="isEdit" :update="updateData">
        <template #thumb="{ rows }">
          <img class="table-td-thumb" :src="rows.thumb"></img>
        </template>
      </TableEdit>
    </el-dialog>
    <el-dialog title="查看详情" v-model="visible1" width="700px" destroy-on-close>
      <TableDetail :data="viewData">
        <template #thumb="{ rows }">
          <el-image :src="rows.thumb"></el-image>
        </template>
      </TableDetail>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="patentList">
import { ref, reactive } from 'vue';
import { ElMessage, } from 'element-plus';
import {CirclePlusFilled, CloseBold, Delete, Edit, Select} from '@element-plus/icons-vue';
import {fetchGetData, fetchPostData} from '@/api';
import TableCustom from '@/components/table-custom.vue';
import TableDetail from '@/components/table-detail.vue';
import TableSearch from '@/components/table-search.vue';
import { TableItem } from '@/types/table';
import { FormOption, FormOptionList } from '@/types/form-option';
//
const techOptions2 = ref([]);
const techOptions1 = ref([]);
// 查询相关
const query = reactive({
  title: '',
  abstractContent: '',
  standardizedApplicant: '',
  patentType: '',
  publicationNumber: '',
  currentOwnerProvince: '',
  currentOwner: '',
  currentLegalStatus: '',
  firstTech: '',
  secondTech: '',
});
const searchOpt = ref<FormOptionList[]>([
  { type: 'input', label: '专利名称：', prop: 'title' },
  { type: 'input', label: '专利摘要：', prop: 'abstractContent' },
  { type: 'input', label: '申请人：', prop: 'currentOwner' },
  { type: 'input', label: '第一技术分类：', prop: 'firstTech' },
  { type: 'input', label: '第二技术分类：', prop: 'secondTech' }
])
const handleSearch = () => {
  changePage(1);
};

// 表格相关
let columns = ref([
  { type: 'selection' },
  { type: 'index', label: '序号', width: 55, align: 'center' },
  { prop: 'publicationNumber', label: '公开号' , width: 15},
  { prop: 'title', label: '专利名称' , width: 250, align: 'left' },
  { prop: 'abstractContent', label: '专利摘要' , width: 250, align: 'left' },
  { prop: 'applicationDate', label: '申请日' , width: 150, align: 'center' },
  { prop: 'firstTech', label: '第一分类' , width: 100, align: 'center' },
  { prop: 'secondTech', label: '第二分类' , width: 200, align: 'center' },
  { prop: 'operator', label: '操作', width: 250 },
  { prop: 'thirdTech', label: '第三分类' , width: 100, align: 'center' },
  { prop: 'patentType', label: '专利类型' , width: 200, align: 'center' },
  { prop: 'applicant', label: '申请人' , width: 250, align: 'left' },
])
const page = reactive({
  index: 1,
  size: 20,
  total: 200,
});

const patentView = (url) => {
  window.open(url, "_blank")
}


const tableData = ref<TableItem[]>([]);
const getData = async () => {
  const res = await fetchPostData("/patentList", {
    'currentPage': page.index,
    'pageSize': 20,
  },{
    'title':query.title,
    'abstract':query.abstractContent,
    'first_tech':query.firstTech,
    'second_tech':query.secondTech,
    'publication_number':query.publicationNumber,
    'current_owner_province':query.currentOwnerProvince,
    'current_owner':query.currentOwner,
    'patent_type':query.patentType,
    'current_legal_status':query.currentLegalStatus,
  }).then((response)=>{
    // 使用 map 函数转换数组中的每个对象
    tableData.value = response.data.data.list.map(item => {
      // 克隆对象以避免直接修改原始数据
      const newItem = {...item};
      // 转换 enable2 字段
      newItem.applicationDate = newItem.applicationDate.slice(0,10);
      newItem.secondTech = newItem.secondTech.split('|');
      // 返回修改后的对象
      return newItem;
    });
    page.total = response.data.data.total;
  }).catch((error)=>{
    console.log(error);
  })
};

getData();


const getTechOptions2 = async (row) => {
  const res = await fetchPostData("/techOption", {},{
    'first_tech': row.firstTech,
    'tech_field':'second_tech'
  }).then((response)=>{
    techOptions2.value = response.data.data.list.map(item => {
      // 克隆对象以避免直接修改原始数据
      const newItem = {...item};
      // 转换 enable2 字段
      newItem.label = item;
      newItem.value = item;
      // 返回修改后的对象
      return newItem;
    });
  }).catch((error)=>{
    console.log(error);
  })
};


const getTechOptions1 = async (row) => {
  const res = await fetchPostData("/techOption", {},{
    'tech_field':'first_tech'
  }).then((response)=>{
    techOptions1.value = response.data.data.list.map(item => {
      // 克隆对象以避免直接修改原始数据
      const newItem = {...item};
      // 转换 enable2 字段
      newItem.label = item;
      newItem.value = item;
      // 返回修改后的对象
      return newItem;
    });
  }).catch((error)=>{
    console.log(error);
  })
};

const changePage = (val: number) => {
  page.index = val;
  getData();
};

// 新增/编辑弹窗相关
let options = ref<FormOption>({
  labelWidth: '100px',
  span: 24,
  list: [
    { type: 'input', label: '用户名', prop: 'name', required: true },
    { type: 'number', label: '账户余额', prop: 'money', required: true },
    { type: 'switch', activeText: '正常', inactiveText: '异常', label: '账户状态', prop: 'state', required: true },
    { type: 'upload', label: '头像', prop: 'thumb', required: true },
  ]
})
const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});

const handleEdit = (row) => {
  getTechOptions1(row);
  getTechOptions2(row);
  rowData.value = { ...row };
  row.editing = true;
};


const saveData = async (row) => {
  const res = await fetchPostData("/updateData", {},{
    'publication_number': row.publicationNumber,
    'first_tech': row.firstTech,
    'second_tech': row.secondTech.join("|")
  }).then((response)=>{

  }).catch((error)=>{
    console.log(error);
  })
};


const handleSave = (row) => {
  rowData.value = { ...row };
  row.editing = false;
  saveData(row);
};

const handleCancel = (row, index) => {
  row.editing = false;
  tableData.value[index] = rowData.value;
};


const updateData = () => {
  closeDialog();
  getData();
};

const closeDialog = () => {
  visible.value = false;
  isEdit.value = false;
};

// 查看详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
  row: {},
  list: []
});
const handleView = (row: TableItem) => {
  viewData.value.row = { ...row }
  viewData.value.list = [
    {
      prop: 'id',
      label: '用户ID',
    },
    {
      prop: 'name',
      label: '用户名',
    },
    {
      prop: 'money',
      label: '账户余额',
    },
    {
      prop: 'state',
      label: '账户状态',
    },
    {
      prop: 'thumb',
      label: '头像',
    },
  ]
  visible1.value = true;
};

// 删除相关
const handleDelete = (row: TableItem) => {
  ElMessage.success('删除成功');
}
</script>

<style scoped>
.link:hover{
  color:#2d8cf0;
  cursor: pointer;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

</style>